package com.scalar.chiptrack.sales.reports.actions;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.process.dao.NewProductDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.reports.forms.RevenueShipmentReportForm;
import com.scalar.chiptrack.users.User;

import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.ExcelUtils;

/**
 * User: Srikanth.C
 * Date: Feb 20, 2007
 * Time: 12:57:25 PM
 */
public class RevenueShipmentReportAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/revenueShipmentReport.do";
    public ActionForward execute( ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response )
            throws Exception
    {

        String action = request.getParameter( "action" );
        HttpSession session = request.getSession();

        User user = ( User ) session.getAttribute( SessionKeys.USER_KEY );

        if( user == null )
        {
            session.setAttribute( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString() );
            return ( mapping.findForward( "login" ) );
        }

        RevenueShipmentReportForm revenueShipmentReportForm = (RevenueShipmentReportForm) form;
        revenueShipmentReportForm=null;
        ArrayList customerList   = null;
        ArrayList productList = null;
        ArrayList statusList = null;
        ArrayList shipmentDetailsList = null;
        Workbook workbook = null;
        String fileName = "";

        if ( action == null )
        {
            action = "";
        }
        try
        {
            if ( "revenueShipmentReport".equalsIgnoreCase(action) || "".equals(action) )
            {
                try
                {
                    //revenueShipmentReportForm.setCustomer("0");
                    customerList = NewCustomerDAO.getAllCustomerNamesByCustomerType( "Customer" );
                    productList = NewProductDAO.loadPartNumbers( null, 0, Constants.LOCATION_TYPE_FG, true, true, false, 0 );
                }
                catch( Exception e )
                {
                    customerList         = new ArrayList();
                    productList           = new ArrayList();
                    e.printStackTrace();
                }

                request.setAttribute( "customerList", customerList );
                request.setAttribute( "productList", productList );
            }
            else if ( "changeLogReport".equalsIgnoreCase(action))
            {
                try
                {
                    customerList = CustomerDAO.getAllCustomerNamesByUserType(null,user);
                    productList = NewProductDAO.loadPartNumbers( null, 0, Constants.LOCATION_TYPE_FG, true, true, false, 0 );
                    statusList = SalesOrderDAO.loadSaleOrdersStatus();

                }
                catch( Exception e )
                {
                    customerList         = new ArrayList();
                    productList           = new ArrayList();

                    e.printStackTrace();
                }

                request.setAttribute( "customerList", customerList );
                request.setAttribute( "productList", productList );
                request.setAttribute( "statusList", statusList );
            }
            else if ( "generateXLSShipmentReport".equalsIgnoreCase(action) )
            {
                String customer = request.getParameter( "prompt0" );
                String productId   = request.getParameter( "prompt1" );
                String soNumber   = request.getParameter( "prompt2" );
                String fromDate= request.getParameter( "prompt3" );
                String toDate = request.getParameter( "prompt4" );
                String category = request.getParameter("prompt5");
                String invoiceNo = request.getParameter("prompt6");
                String reportType = request.getParameter( "prompt7" );
                String defaultPrompt= request.getParameter( "prompt8" );

                shipmentDetailsList = NewCustomerDAO.getInvoiceDetails( null,customer,productId,soNumber,fromDate,toDate,reportType,category, invoiceNo, defaultPrompt);
                workbook =  DataDumpReportsHelper.getWorkbook( shipmentDetailsList, "Invoice Report", fromDate, toDate, null );
                fileName = "InvoiceReport_"+DateUtil.getTimeStamp();

                ExcelUtils.generateExcelReport( workbook, fileName, response);
            }
            else if ( "generateCSVShipmentReport".equalsIgnoreCase(action) )
            {
                String customer = request.getParameter( "prompt0" );
                String productId   = request.getParameter( "prompt1" );
                String soNumber   = request.getParameter( "prompt2" );
                String fromDate= request.getParameter( "prompt3" );
                String toDate = request.getParameter( "prompt4" );
                String category = request.getParameter("prompt5");
                String invoiceNo = request.getParameter("prompt6");
                String reportType = request.getParameter( "prompt7" );
                String defaultPrompt= request.getParameter( "prompt8" );

                String csvString = NewCustomerDAO.getInvoiceDetailsCSV( null,customer,productId,soNumber,fromDate,toDate,reportType,category, invoiceNo, defaultPrompt);
                fileName = "InvoiceReport_"+ DateUtil.getTimeStamp() + ".csv";
                try
                {
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-Disposition", "attachment; filename=" + fileName  + ";");
                    response.getOutputStream().print(csvString);
                    csvString = null;
                    response.getOutputStream().flush();
                }
                catch( Exception innerExcep )
                {
                    String stackTrace = innerExcep.toString();
                    if ( stackTrace.indexOf("socket write error") > -1 || stackTrace.indexOf("Socket closed") > -1 )
                    {
                        System.out.println("## Export to CSV ClientAbortException ##");
                        //Logger.error( "## Export to Excel ClientAbortException ##", innerExcep );
                    }
                    else
                    {
                        throw innerExcep;
                    }
                }
				finally
				{
					response.getOutputStream().close();
				}
            }
        }
        catch ( Exception e)
        {
            e.printStackTrace();
        }

        if ( "revenueShipmentReport".equalsIgnoreCase(action) )
        {
            return ( mapping.findForward( "revenueShipmentReport" ) );
        }
        else if ( "changeLogReport".equalsIgnoreCase(action))
        {
            return ( mapping.findForward( "changeLogReport" ) );
        }
        return null;
    }

    public ArrayList getCustomerStatus()
    {
        ArrayList statusList = new ArrayList();
        statusList.add ( new LabelValueBean("Active","Active"));
        statusList.add ( new LabelValueBean("Disable","Disable"));
        return  statusList;
    }

}
